import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/index.js'

Vue.use(Router)

//路由懒加载
const Login = resolve => {
  require.ensure(['@/components/Login.vue'], () => {
    resolve(require('@/components/Login.vue'));
  });
};

const Register = resolve => {
  require.ensure(['@/components/Register.vue'], () => {
    resolve(require('@/components/Register.vue'));
  });
};

const Index = resolve => {
  require.ensure(['@/components/Index.vue'], () => {
    resolve(require('@/components/Index.vue'));
  });
};

//主功能
const Goodlist = resolve => {
  require.ensure(['@/components/Main/Goodlist.vue'], () => {
    resolve(require('@/components/Main/Goodlist.vue'));
  });
};
const addgood = resolve => {
  require.ensure(['@/components/Main/addgood.vue'], () => {
    resolve(require('@/components/Main/addgood.vue'));
  });
};
const rootsetting = resolve => {
  require.ensure(['@/components/setting/rootsetting.vue'], () => {
    resolve(require('@/components/setting/rootsetting.vue'));
  });
};
const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
      hidden:true
    },
    {
      path: '/register',
      name: 'register',
      component: Register,
      hidden:true
    },
    // {
    //   path: '/addgood/:id',
    //   name: 'addgood',
    //   component: addgood,
    //   hidden:true
    // },
    {
      path: '/',
      name: '商品管理',
      component: Index,
      meta: {
        requiresAuth: true
      },
      leaf: false,
      iconCls: 'el-icon-date',
      children: [
          { path: '/goodlist', component: Goodlist, name: '商品列表'},
          { path: '/addgood/:id', component: addgood, name: '添加商品'}
      ]
    },
    {
      path: '/',
      component: Index,
      name: '系统管理',
      meta: {
        requiresAuth: true
      },
      leaf: true,//只有一个节点
      iconCls: 'el-icon-menu',
      children: [
          { path: '/rootsetting', component: rootsetting, name: '权限管理' }
      ]
    },
    
    
  ]
});


//注册全局钩子用来拦截导航
router.beforeEach((to, from, next) => {
  //判断要去的路由有没有requiresAuth
  if (to.meta.requiresAuth) {
    if(localStorage.getItem('userlogin')){
      next();
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }  // 将刚刚要去的路由path（却无权限）作为参数，方便登录成功后直接跳转到该路由
      });
    }

  } else {
    next();//如果无需token,那么随它去吧
  }
});
export default router
